//当前的页码
var page = 1;
//每页的条数
var count = 8;
//获取tbody
var oTBody = document.querySelector("tbody");
//获取分页容器
var oPagination = document.querySelector(".pagination");
//获取上一页的按钮
var oPrevBtn = document.querySelector(".prev");
//获取下一页的按钮
var oNextBtn = document.querySelector(".next");

//获取搜索的输入框
var oSearchInp1 = document.querySelector("#entityApplyId");
var oSearchInp2 = document.querySelector("#receiveId");
var oSearchInp3 = document.querySelector("#idCard");
var oSearchInp4 = document.querySelector("#borrowerName");
var oSearchInp5 = document.querySelector("#startTime");
//获取审批结果
var oSearchInp6 = document.querySelector("#dropdownMenu1");
//获取搜索按钮
var oSearchBtn = document.querySelector("#search");

//获取添加的保存按钮
var oAddSaveBtn = document.querySelector(".addSaveBtn");
//获取重置按钮
var oResetBtn = document.querySelector("#reset");

// 左侧导航
// 有子菜单的项（包括菜单项和子菜单列表）                        一级菜单有子菜单的li标签
let subMenus = document.querySelectorAll('.menus-submenu');
// 菜单项X                                                    一级菜单里的a标签
let subMenusItems = document.querySelectorAll('.menus-submenu > .menus-item');
// 子菜单列表                                                 二级菜单ul
let subMenusList = document.querySelectorAll('.menus-submenu > .menus-list');
// 没有子菜单的项                                              一级菜单没有子菜单的li标签
let noSubMenusItems = document.querySelectorAll('.menus-nosubmenu');
let expandedIndex = 0;// 当前展开的菜单项索引
let selectedParentIndex = 0;// 当前选择的 子菜单项 的 父菜单项 索引
let selectedSubIndex = 0;// 当前选择的子菜单项索引
let selectedNoIndex = -1;// 当前选择的 没有子菜单的项 的索引

function closeExpanded(index) {
  // 关闭展开
  subMenus[index].classList.remove('expanded-list');
}
function clearSelected() {
  // 清除选中项
  // 选中项有子菜单时
  if (-1 != selectedParentIndex) {
    subMenusList[selectedParentIndex].getElementsByTagName('li')[selectedSubIndex].classList.remove('selected-items')
    subMenus[selectedParentIndex].classList.remove('selected-items')
  }
  // 选中项没有子菜单时
  else {
    noSubMenusItems[selectedNoIndex].classList.remove('selected-items')
  }
}
function initListeners() {
  // 点击响应：菜单项展开
  for (let index = 0; index < subMenusItems.length; index++) {
    subMenusItems[index].addEventListener('click', function (e) {
      // 当前点击的没有展开 并且 存在展开的, 关闭当前展开的
      if (index != expandedIndex && -1 != expandedIndex) {
        closeExpanded(expandedIndex)
      }

      // 判断点击的是否已经展开
      if (!subMenus[index].classList.toggle('expanded-list')) {
        // 点击的就是展开的，关闭展开
        expandedIndex = -1
        // 选中的项 是否是当前点击的子项
        if (index == selectedParentIndex) {
          subMenus[index].classList.add("selected-items")
        }
      }
      else {
        // 点击的是其他
        expandedIndex = index
        // 选中的项 是否是当前点击的子项
        if (index == selectedParentIndex) {
          subMenus[selectedParentIndex].classList.remove("selected-items")
        }
        else if (-1 != selectedParentIndex) {
          subMenus[selectedParentIndex].classList.add("selected-items")
        }
      }
    })
  }
  // 点击响应：子菜单项选中
  for (let index = 0; index < subMenusList.length; index++) {
    let subMenuLi = subMenusList[index].getElementsByTagName('li')
    for (let j = 0; j < subMenuLi.length; j++) {
      subMenuLi[j].addEventListener('click', function (e) {
        if (!subMenuLi[j].classList.contains('selected-items')) {
          // 清除选择
          clearSelected()

          subMenuLi[j].classList.add('selected-items')
          selectedParentIndex = index
          selectedSubIndex = j
        }
      })
    }
  }
  // 点击响应：无二级菜单的菜单项选中
  for (let index = 0; index < noSubMenusItems.length; index++) {
    noSubMenusItems[index].addEventListener("click", function (e) {
      if (!this.classList.contains('selected-items')) {
        // 清除选择
        clearSelected()
        // 如果有展开，关闭展开
        if (-1 != expandedIndex && subMenus[expandedIndex].classList.contains('expanded-list')) {
          closeExpanded(expandedIndex)
        }
        this.classList.add('selected-items')
        selectedNoIndex = index
        selectedParentIndex = -1
      }
    })
  }
}
initListeners()


// 顶部导航栏隐藏
var oLeft = document.querySelector(".container-fluid>.left");
var oRight = document.querySelector(".container-fluid>.right");
var oMenu = document.querySelector(".header-left");
oMenu.addEventListener("click", hideDisplayFn);
var flag = true;
function hideDisplayFn() {
  if (flag) {
    oLeft.style.display = "none";
    oRight.style.width = "100%";
    flag = false;
  } else {
    oLeft.style.display = "block";
    oRight.style.width = "calc(100% - 256px)";
    flag = true;
  }
}

// 审批结果
var oDropdown = document.querySelector('.dropdown');
oDropdown.addEventListener('click', changeFn);
function changeFn() {
  if (event.target.className == 'underapproval') {
    oDropdown.children[0].innerHTML = '审批中<span class="caret"></span>';
  } else if (event.target.className == 'rejection') {
    oDropdown.children[0].innerHTML = '审批驳回<span class="caret"></span>';
  } else if (event.target.className == 'approved') {
    oDropdown.children[0].innerHTML = '审批通过<span class="caret"></span>';
  } else {
    oDropdown.children[0].innerHTML = '请选择<span class="caret"></span>';
  }
}

// 表格数据渲染
var data = [
  {
    id: 1,
    entityapplyid: "202207050001",
    receiveid: "20220704001",
    borrowername: '王志勇',
    idcard: '511025200001112345',
    applytime: '2022-1-4 17:14:12',
    borrowdate: 2,
    approvalResult: '审批驳回',
    remarks: "备注说明展示",
  },
  {
    id: 2,
    entityapplyid: "202207050002",
    receiveid: "20220704002",
    borrowername: 'Lucky',
    idcard: '511025200001112345',
    applytime: '2022-2-4 17:14:12',
    borrowdate: 2,
    approvalResult: '审批驳回',
    remarks: "备注说明展示",
  },
  {
    id: 3,
    entityapplyid: "202207050004",
    receiveid: "20220704001",
    borrowername: 'Nini',
    idcard: '511025200001112345',
    applytime: '2022-3-4 17:14:12',
    borrowdate: 2,
    approvalResult: '审批通过',
    remarks: "备注说明展示",
  },
  {
    id: 4,
    entityapplyid: "202207050004",
    receiveid: "20220704004",
    borrowername: '李四',
    idcard: '511025200001112345',
    applytime: '2022-4-4 17:14:12',
    borrowdate: 2,
    approvalResult: '审批中',
    remarks: "备注说明展示",
  },
  {
    id: 5,
    entityapplyid: "202207050005",
    receiveid: "20220704005",
    borrowername: '王五',
    idcard: '511025200001112345',
    applytime: '2022-5-4 17:14:12',
    borrowdate: 2,
    approvalResult: '审批中',
    remarks: "备注说明展示",
  },
  {
    id: 6,
    entityapplyid: "202207050006",
    receiveid: "20220704006",
    borrowername: '祝六',
    idcard: '511025200001112345',
    applytime: '2022-6-4 17:14:12',
    borrowdate: 2,
    approvalResult: '审批驳回',
    remarks: "备注说明展示",
  },
  {
    id: 7,
    entityapplyid: "202207050007",
    receiveid: "20220704007",
    borrowername: '静静',
    idcard: '511025200001112345',
    applytime: '2022-7-4 17:14:12',
    borrowdate: 2,
    approvalResult: '审批中',
    remarks: "备注说明展示",
  },
  {
    id: 8,
    entityapplyid: "202207050008",
    receiveid: "20220704009",
    borrowername: '花花',
    idcard: '511025200001112345',
    applytime: '2022-8-4 17:14:12',
    borrowdate: 2,
    approvalResult: '审批通过',
    remarks: "备注说明展示",
  },
  {
    id: 9,
    entityapplyid: "202207050009",
    receiveid: "20220704008",
    borrowername: '蹦蹦',
    idcard: '511025200001112345',
    applytime: '2022-9-4 17:14:12',
    borrowdate: 2,
    approvalResult: '审批中',
    remarks: "备注说明展示",
  },
  {
    id: 10,
    entityapplyid: "202207050010",
    receiveid: "20220704010",
    borrowername: '跳跳',
    idcard: '511025200001112345',
    applytime: '2022-10-4 17:14:12',
    borrowdate: 2,
    approvalResult: '审批驳回',
    remarks: "备注说明展示",
  },

];
// localStorage.setItem("data", JSON.stringify(data));
function render() {
  //查看搜索框的内容
  var str1 = oSearchInp1.value.trim();
  var str2 = oSearchInp2.value.trim();
  var str3 = oSearchInp3.value.trim();
  var str4 = oSearchInp4.value.trim();
  var str5 = oSearchInp5.value.trim();
  var str6 = oSearchInp6.innerText.trim();

  var searchData = []; //最终用来渲染的;
  var data1 = [];
  var data2 = [];
  var data3 = [];
  var data4 = [];
  var data5 = [];

  if (str1 == '') {
    data1 = data;
  } else (
    data1 = data.filter(function (v) {
      return v.entityapplyid.includes(str1);
    })
  )
  if (str2 == '') {
    data2 = data1;
  } else (
    data2 = data1.filter(function (v) {
      return v.receiveid.includes(str2);
    })
  )
  if (str3 == '') {
    data3 = data2;
  } else (
    data3 = data2.filter(function (v) {
      return v.idcard.includes(str3);
    })
  )
  if (str4 == '') {
    data4 = data3;
  } else (
    data4 = data3.filter(function (v) {
      return v.borrowername.includes(str4);
    })
  )
  if (str5 == '') {
    data5 = data4;
  } else (
    data5 = data4.filter(function (v) {
      return v.applytime.includes(str5);
    })
  )
  if (str6 == '请选择') {
    searchData = data5;
  } else {
    searchData = data5.filter(function (v) {
      return v.approvalResult.startsWith(str6);
    })
  }
  // console.log(data1);
  // console.log(data2);
  // console.log(searchData);
  //让table为空
  oTBody.innerHTML = "";
  //根据count和page准备要渲染的数据
  var renderArr = searchData.slice((page - 1) * count, page * count);
  //循环要渲染的数据
  for (var i = 0; i < renderArr.length; i++) {
    var oTr = document.createElement("tr");
    oTr.innerHTML = `
            <tr>
                <td>${renderArr[i].id}</td>
                <td>${renderArr[i].entityapplyid}</td>
                <td>${renderArr[i].receiveid}</td>
                <td>${renderArr[i].borrowername}</td>
                <td>${renderArr[i].applytime}</td>
                <td>${renderArr[i].borrowdate}</td>
                <td>${renderArr[i].approvalResult}</td>
                <td>${renderArr[i].remarks}</td>
            </tr>
        `;
    oTBody.appendChild(oTr);
  }

  //渲染页码
  //找到所有的1，2，3，4的页码
  var aPageBtn = document.querySelectorAll(".pageBtn");
  //删除所有的页码
  for (var i = 0; i < aPageBtn.length; i++) {
    oPagination.removeChild(aPageBtn[i].parentNode);
  }
  //根据数据的长度重新创建页码
  for (var i = 1; i <= Math.ceil(searchData.length / count); i++) {
    //创建li
    var oLi = document.createElement("li");
    //给li创建内容
    oLi.innerHTML = `<a class="pageBtn" href="#">${i}</a>`;
    //如果li和当前的页码一致，给他加一个选中的class
    if (i == page) {
      oLi.classList.add("active");
    }
    //在下一页的前面插入页码
    oPagination.insertBefore(oLi, oPagination.lastElementChild);
  }
}
render();

//给分页加事件
oPagination.addEventListener("click", changePage);
function changePage() {
  //如果当前点击的按钮有pageBtn这个class名字
  if (event.target.className == "pageBtn") {
    //修改全局的page
    page = event.target.innerText;
    //渲染table，渲染分页
    render();
  }
}
//给上一页和下一页加事件
oPrevBtn.addEventListener("click", prev);
oNextBtn.addEventListener("click", next);
function prev() {
  if (page > 1) {
    page--;
    render();
  }
}
function next() {
  if (page < Math.ceil(data.length / count)) {
    page++;
    render();
  }
}

// 添加
//添加的时候
oAddSaveBtn.addEventListener('click', addFn);
function addFn() {
  var addId = Number(data[data.length - 1].id) + 1;
  var addEntityApplyId = Number(data[data.length - 1].entityapplyid) + 1;
  var addReceiveId = document.querySelector('.addReceiveId').value;
  var addBorrowerName = document.querySelector('.addBorrowerName').value;
  var addIdCard = document.querySelector('.addIdCard').value;
  var addApplyTime = document.querySelector('.addApplyTime').value;
  var addBorrowDate = document.querySelector('.addBorrowDate').value;
  var addRemarks = document.querySelector('.addRemarks').value;

  data.push({
    id: addId,
    entityapplyid: addEntityApplyId,
    receiveid: addReceiveId,
    borrowername: addBorrowerName,
    idcard: addIdCard,
    applytime: addApplyTime,
    borrowdate: addBorrowDate,
    approvalResult: '审批中',
    remarks: addRemarks,
  })

  render();
  //让模态框隐藏
  $('#addModal').modal('hide')
}

//点击重置
oResetBtn.addEventListener('click', resetFn);
function resetFn() {
  oSearchInp1.value = '';
  oSearchInp2.value = '';
  oSearchInp3.value = '';
  oSearchInp4.value = '';
  oSearchInp5.value = '';
  oSearchInp6.innerHTML = '请选择<span class="caret"></span>';
  render();
}

// 查询
oSearchBtn.addEventListener('click', searchFn);
function searchFn() {
  page = 1;
  render();
}